package com.cn.book.filter;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class JwtUtil {

    public static final String SECRET = "qazwsx123444$#%#()*&& asdaswwi1235 ?;!@#kmmmpom in***xx**&";
    public static final String TOKEN_PREFIX = "qazyhn";
    public static final String HEADER_AUTH = "Authorization";

    public static String generateToken(String user) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", new Random().nextInt());
        map.put("user", user);
        String jwt = Jwts.builder()
                .setSubject("user_info")
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return TOKEN_PREFIX + jwt;
    }

    public static Map<String, String> validateToken(String token) {
        if (token == null) {
            throw new PermissionException("token is error, please check");
        }

        Map<String, String> map = new HashMap<>();
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token.substring(6, token.length()))
                .getBody();
        Object id = body.get("id");
        Object user = body.get("user");
        map.put("id", id == null ? null : id.toString());
        map.put("user", user == null ? null : user.toString());
        if (user == null) {
            throw new PermissionException("user is null");
        }
        return map;
    }
}
